<template>
  <div>
    <div
      v-loading="datacardLoading"
      v-if="
        resourceSet.includes(
          '/web/data-statistic/chargingDataStatistic/订单数据统计'
        )
      "
      class="datacard-search-wrapper"
    >
      <div class="panel">
        <div class="panel-header">充电数据统计</div>
        <div class="form-wrapper">
          <div class="form-content">
            <i-form
              class="iform"
              :layoutSpan="layoutSpan"
              :labelWidth="labelWidth"
              :breakpoint="breakpoint"
              :inline="true"
              :items="queryFormItems"
              :form="queryForm"
              :rules="queryFormRules"
            >
              <template slot="date">
                <el-form-item prop="date">
                  <SearchDatePicker
                    type="month"
                    :start.sync="queryForm.startTime"
                    :end.sync="queryForm.endTime"
                    :disable-date="disableDate"
                  />
                </el-form-item>
              </template>
              <template slot="address">
                <el-form-item>
                  <HycAddressCascader
                    v-model="queryForm.area"
                    :level="0"
                    :clearable="true"
                    size="small"
                  />
                </el-form-item>
              </template>
              <template slot="merchant" v-if="queryForm.containSubMch">
                <el-form-item>
                  <SearchMerchants
                    v-model="queryForm.mchUserId"
                    :defaultOptions="false"
                    size="small"
                  />
                </el-form-item>
              </template>
            </i-form>
            <div class="btn-wrapper">
              <el-button type="primary" size="small" @click="initDataCard">
                查询
              </el-button>
              <el-button size="small" @click="reset">重置</el-button>
            </div>
          </div>
        </div>
      </div>
      <DataCard
        :data="dataCard"
        :items="dataCardItems"
        :tips="tips"
        @handleChange="initDataCard"
      />
    </div>
    <div
      v-if="
        resourceSet.includes(
          '/web/data-statistic/chargingDataStatistic/每日套餐订购数'
        )
      "
      v-loading="dayTimeLoading"
    >
      <EchartPanel
        :timeUnit="'date'"
        @handleTableData="handleDayTimecardTableData"
        :echartsOption="dayTimecardEchartsOption"
        title="每日套餐订购数"
      />
    </div>
    <div
      v-loading="monthTimeLoading"
      v-if="
        resourceSet.includes(
          '/web/data-statistic/chargingDataStatistic/每月套餐订购数'
        )
      "
    >
      <EchartPanel
        :timeUnit="'month'"
        @handleTableData="handleMonthTimecardTableData"
        :echartsOption="monthTimecardEchartsOption"
        title="每月套餐订购数"
      />
    </div>
    <div
      v-loading="dayChargeLoading"
      v-if="
        resourceSet.includes(
          '/web/data-statistic/chargingDataStatistic/每日充电时长走势图'
        )
      "
    >
      <EchartPanel
        :timeUnit="'date'"
        @handleTableData="handleDayChargeTimeTableData"
        :echartsOption="dayChargeTimeEchartsOption"
        title="每日充电时长"
      />
    </div>
    <div
      v-loading="monthChargeLoading"
      v-if="
        resourceSet.includes(
          '/web/data-statistic/chargingDataStatistic/每月充电时长走势图'
        )
      "
    >
      <EchartPanel
        :timeUnit="'month'"
        @handleTableData="handleMonthChargeTimeTableData"
        :echartsOption="monthChargeTimeEchartsOption"
        title="每月充电时长"
      />
    </div>
    <div
      v-loading="dayEleLoading"
      v-if="
        resourceSet.includes(
          '/web/data-statistic/chargingDataStatistic/每日充电量走势图'
        )
      "
    >
      <EchartPanel
        :timeUnit="'date'"
        @handleTableData="handleDayElectricityStatisticTableData"
        :echartsOption="dayElectricityStatisticEchartsOption"
        title="每日充电量"
      />
    </div>
    <div
      v-loading="monthEleLoading"
      v-if="
        resourceSet.includes(
          '/web/data-statistic/chargingDataStatistic/每月充电量走势图'
        )
      "
    >
      <EchartPanel
        :timeUnit="'month'"
        @handleTableData="handleMonthElectricityStatisticTableData"
        :echartsOption="MonthElectricityStatisticEchartsOption"
        title="每月充电量"
      />
    </div>
    <div
      v-loading="provinceLoading"
      v-if="
        resourceSet.includes(
          '/web/data-statistic/chargingDataStatistic/各省端口平均充电时长走势图'
        )
      "
    >
      <EchartPanel
        :timeUnit="'date'"
        @handleTableData="handleProvinceData"
        :echartsOption="provinceEchartsOption"
        title="各省端口平均充电时长"
        :defaultFormItems="['merchantCheckbox', 'merchant']"
        :formItemsInline="formItems"
        :customReset="true"
        @handleReset="handleProvinceReset"
        :rangeButton="false"
      >
        <template slot="month">
          <el-form-item>
            <el-date-picker
              v-model="month"
              type="month"
              placeholder="请选择月份"
            />
          </el-form-item>
        </template>
      </EchartPanel>
    </div>
  </div>
</template>
<script>
import HycAddressCascader from '@/components/hycAddressCascader'
import SearchMerchants from '@/components/SearchMerchants'
import EchartPanel from '@/components/EchartPanel'
import {
  singleBarOption,
  barOption,
  bar_lineOption,
  multiBar_lineOption,
} from './func/options'
import {
  handleDayTimecardTableData,
  handleMonthTimecardTableData,
  handleDayChargeTimeTableData,
  handleMonthChargeTimeTableData,
  handleDayElectricityStatisticTableData,
  handleMonthElectricityStatisticTableData,
  handleProvinceData,
} from './func/chargeQuery'
import { orderDataStatistic } from '@/api/chargeStatistics'
import DataCard from './components/DataCard'
import dayjs from 'dayjs'

export default {
  name: 'VisualizationCharge',
  components: { HycAddressCascader, SearchMerchants, EchartPanel, DataCard },
  computed: {
    resourceSet() {
      return this.$store.getters.resourceSet
    },
  },
  data() {
    return {
      layoutSpan: 24,
      labelWidth: 20,
      breakpoint: [
        [768, 1],
        [992, 2],
        [1200, 2],
        [1920, 3],
        [Infinity, 4],
      ],
      queryForm: {
        containSubMch: true,
        mchUserId: '',
        startTime: null,
        endTime: null,
        area: {},
      },
      queryFormItems: [
        {
          slot: 'date',
        },
        {
          slot: 'address',
        },
        {
          slot: 'merchant',
        },
      ],
      disableDate: {
        startTime: dayjs('2024-01-01').valueOf(),
        endTime: dayjs().endOf('month').valueOf(),
      },
      queryFormRules: {
        date: [
          {
            validator: (rule, value, callback) => {
              if (this.queryForm.startTime && !this.queryForm.endTime) {
                callback(new Error('请选择结束时间'))
                return false
              }
              if (!this.queryForm.startTime && this.queryForm.endTime) {
                callback(new Error('请选择开始时间'))
                return false
              }
              callback()
            },
          },
        ],
      },
      datacardLoading: false,
      dataCard: {
        totalIncome: 0,
        totalMonthlyCardIncome: 0,
        totalServiceIncome: 0,
        totalUnPayedBillAmount: 0,
        totalZeroIncome: 0,
      },
      dataCardItems: [
        {
          label: '总充电时长',
          unit: '分',
          formatter: (data) => {
            return (
              data.totalDurationSum &&
              Number(data.totalDurationSum).toLocaleString('zh-CN', {
                maximumFractionDigits: 2, // 最多显示两位小数
              })
            )
          },
        },
        {
          label: '总用电量',
          unit: '度',
          formatter: (data) => {
            return (
              data.totalElectricitySum &&
              Number(data.totalElectricitySum).toLocaleString('zh-CN', {
                maximumFractionDigits: 2, // 最多显示两位小数
              })
            )
          },
        },
        /*{
          label: '总收益统计',
          symbol: '￥',
          unit: '元',
          formatter: (data) => {
            return (
              data.totalIncome &&
              Number(data.totalIncome.toFixed(2)).toLocaleString()
            )
          },
        },
        {
          label: '临充总收入',
          symbol: '￥',
          unit: '元',
          formatter: (data) => {
            return (
              data.totalZeroIncome &&
              Number(data.totalZeroIncome.toFixed(2)).toLocaleString()
            )
          },
        },
        {
          label: '时长卡总收入',
          symbol: '￥',
          unit: '元',
          formatter: (data) => {
            return (
              data.totalMonthlyCardIncome &&
              Number(data.totalMonthlyCardIncome.toFixed(2)).toLocaleString()
            )
          },
        },
        {
          label: '服务费总收入',
          symbol: '￥',
          unit: '元',
          formatter: (data) => {
            return (
              data.totalServiceIncome &&
              Number(data.totalServiceIncome.toFixed(2)).toLocaleString()
            )
          },
        },
        {
          label: '和能量总收入',
          symbol: '￥',
          unit: '元',
          formatter: (data) => {
            return (
              data.totalAndEnergyIncome &&
              Number(data.totalAndEnergyIncome.toFixed(2)).toLocaleString()
            )
          },
        },
        {
          label: '总未支付订单',
          symbol: '￥',
          unit: '元',
          formatter: (data) => {
            return (
              data.totalUnPayedBillAmount &&
              Number(data.totalUnPayedBillAmount.toFixed(2)).toLocaleString()
            )
          },
        },*/
      ],
      tips: [
        // '数据统计截止前一天',
        // '总收益=当期订单用户 临充消费 + 服务费 - 当期电费成本',
        // '总未支付订单：后付费模式中未支付订单总额;',
        // '临充收费 = 当期余额消费 + 当期第三方消费 + 当期预支付已使用 - 服务费',
      ],
      dayTimecardEchartsOption: barOption,
      dayTimeLoading: false,
      monthTimecardEchartsOption: multiBar_lineOption,
      monthTimeLoading: false,
      dayChargeTimeEchartsOption: singleBarOption,
      dayChargeLoading: false,
      monthChargeTimeEchartsOption: bar_lineOption,
      monthChargeLoading: false,
      dayElectricityStatisticEchartsOption: singleBarOption,
      dayEleLoading: false,
      MonthElectricityStatisticEchartsOption: bar_lineOption,
      monthEleLoading: false,
      provinceEchartsOption: bar_lineOption,
      provinceLoading: false,
      formItems: [
        {
          slot: 'month',
        },
      ],
      month: new Date().valueOf(),
    }
  },
  mounted() {
    // this.datacardLoading = true
    // orderDataStatistic({
    //   containSubMch: true,
    // })
    //   .then((res) => {
    //     this.dataCard = res
    //   })
    //   .catch((err) => {
    //     console.log(err)
    //   })
    //   .finally(() => {
    //     this.datacardLoading = false
    //   })
    this.initDataCard()
  },
  methods: {
    reset() {
      this.queryForm = {
        containSubMch: true,
        startTime: null,
        endTime: null,
        area: {},
        mchUserId: '',
      }
    },
    initDataCard() {
      this.datacardLoading = true
      const { containSubMch, mchUserId, startTime, endTime, area } =
        this.queryForm
      const params = {
        containSubMch,
        ...(mchUserId && { mchUserId }),
        ...(startTime && { startTime }),
        ...(endTime && { endTime }),
        ...(area && { province: area.province }),
      }
      orderDataStatistic(params)
        .then((res) => {
          this.dataCard = res
        })
        .catch((err) => {
          console.log(err)
        })
        .finally(() => {
          this.datacardLoading = false
        })
    },
    handleDayTimecardTableData(params, instance) {
      this.dayTimeLoading = true
      handleDayTimecardTableData(params, instance, () => {
        this.dayTimeLoading = false
      })
    },
    handleMonthTimecardTableData(params, instance) {
      this.monthTimeLoading = true
      handleMonthTimecardTableData(params, instance, () => {
        this.monthTimeLoading = false
      })
    },
    handleDayChargeTimeTableData(params, instance) {
      this.dayChargeLoading = true
      handleDayChargeTimeTableData(params, instance, () => {
        this.dayChargeLoading = false
      })
    },
    handleMonthChargeTimeTableData(params, instance) {
      this.monthChargeLoading = true
      handleMonthChargeTimeTableData(params, instance, () => {
        this.monthChargeLoading = false
      })
    },
    handleDayElectricityStatisticTableData(params, instance) {
      this.dayEleLoading = true
      handleDayElectricityStatisticTableData(params, instance, () => {
        this.dayEleLoading = false
      })
    },
    handleMonthElectricityStatisticTableData(params, instance) {
      this.monthEleLoading = true
      handleMonthElectricityStatisticTableData(params, instance, () => {
        this.monthEleLoading = false
      })
    },
    handleProvinceData(params, instance) {
      this.provinceLoading = true
      params.month = dayjs(this.month).valueOf()
      delete params.startTime
      delete params.endTime
      handleProvinceData(params, instance, () => {
        this.provinceLoading = false
      })
    },
    handleProvinceReset(form) {
      this.month = new Date().valueOf()
      form.mchUserId = ''
    },
  },
}
</script>
<style lang="scss" scoped>
.datacard-search-wrapper {
  .form-wrapper {
    background: #fff;
    .form-content {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      margin-left: -12px;
    }
    .iform {
      flex: 1;
      margin-left: 16px;
      margin-top: -5px;
    }
    .btn-wrapper {
      min-width: 130px;
      margin: 0 24px;
      .dash-control {
        cursor: pointer;
        margin: 0 5px;
        display: inline-block;
      }
    }
  }
  .data-card {
    margin: 40px 0 40px;
  }
}
</style>
